package com.youlian.cloud.common.feign.intercepor;

import com.dianping.cat.Cat;
import com.youlian.cloud.log.utils.CatMsgConstants;
import com.youlian.cloud.log.utils.CatMsgContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 为每一个Feign请求做一层拦截
 *
 * @author : liukx
 * @create : 2018/7/10 13:54
 * @email : liukx@elab-plus.com
 */
@Component
public class FeignInterceptor implements RequestInterceptor {

    private Logger logger = LoggerFactory.getLogger(FeignInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            CatMsgContext context = new CatMsgContext();
            Cat.logRemoteCallClient(context);
            requestTemplate.header(Cat.Context.PARENT, context.getProperty(Cat.Context.PARENT));
            requestTemplate.header(Cat.Context.ROOT, context.getProperty(Cat.Context.ROOT));
            requestTemplate.header(Cat.Context.CHILD, context.getProperty(Cat.Context.CHILD));
            requestTemplate.header(CatMsgConstants.APPLICATION_KEY, Cat.getManager().getDomain());
            addHead(requestTemplate);
            logger.debug("构建feign消息树 ... ");

        }
        logger.info(" 开始Feign远程调用 : 请求路径 : " + requestTemplate.url() + " 请求类型 : " + requestTemplate.method());
    }


    /**
     * 将当前上下文的head带到feign的请求head中去
     *
     * @param requestTemplate
     */
    private void addHead(RequestTemplate requestTemplate) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            requestTemplate.header(key, value);
        }
    }
}